<?php

namespace app\utils\ui\native_element;

use app\utils\ui\UIView;
use app\utils\ui\VueView;
use Exception;

class Element implements UIView{

    /**
     * @var array|UIView
     */
    public $child;
    /**
     * @var array
     */
    public $attr;

    /**
     * @var bool 是否需要结束符
     */
    public $endTag;

    public $tagName;

    /**
     * @param string $tagName
     * @param array $attr
     * @param array|UIView $child
     */
    public function __construct(string $tagName,bool $endTag,array $attr=[],$child=null) 
    {
        if(htmlentities($tagName)!=$tagName){
            throw new Exception('错误tag '.$tagName);
        }
        $this->tagName=$tagName;
        $this->endTag=$endTag;
        $this->attr=$attr;
        $this->child=$child;
    }

    public function render(){

        $attr_text='';
        if($this->attr){
            foreach($this->attr as $name=>$value){
                if(is_array($value)){
                    $attr_text.=$name.'="'.json_encode($value,JSON_UNESCAPED_UNICODE).'" ';
                }else{
                    $attr_text.=$name.'="'.$value.'" ';
                }
            }
        }

        $html_start = '<'.$this->tagName.' '.$attr_text.(!$this->endTag ? '/' : '').'>';
        $html_end = $this->endTag ? '</'.$this->tagName.'>' : '';

        $html2='';
        if($this->child){
            if(is_array($this->child)){
                foreach($this->child as $child2){
                    if($child2 instanceof UIView){
                        $html2.=$child2->render();
                    }
                }
            }else{
                $html2=$this->child->render();
            }
        }

        return $html_start.PHP_EOL.$html2.PHP_EOL.$html_end;
    }
    
    public function data(){
        if($this->child){
            if(is_array($this->child)){
                $list = array();
                foreach($this->child as $child){
                    if($child instanceof UIView){
                        $list = array_merge($list,$child->data());
                    }
                }
                return $list;
            }else{
                return $this->child->data();
            }
        }
        return array();
    }

    /**
     * vueview 需要
     */
    public function method()
    {
        $list=array();
        if(is_array($this->child)){
            foreach($this->child as $child){
                if($child instanceof VueView){
                    $list2 = $child->method();
                    foreach($list2 as $v){
                        $list[]=$v;
                    }
                }
            }
        }
        if($this->child instanceof VueView){
            $list2 = $this->child->method();
            foreach($list2 as $v){
                $list[]=$v;
            }
        }
        return $list;
    }
    
}